﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using LibQuestionIs.Managers;
using LibQuestionIs.Models;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;

namespace Infos.InterviewApp.View
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MasterPage : Infos.InterviewApp.Common.LayoutAwarePage
    {
        public ObservableCollection<TipologiaTest> ListTipologiaTest { get; set; }

        public MasterPage()
        {
            this.InitializeComponent();
            PopupBacheca = new Popup()
            {
                Margin = new Thickness(100, 100, 100, 100),
                VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch,
                HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch,
            };
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            DataFlowObject.IsRegistrato = false;

            ManagerRoamingState MRS = new ManagerRoamingState();
            String esito = await MRS.Leggi();
            Progress.IsActive = true;
            AnimazioneSBHeader();

            if (!DataFlowObject.IsDatiCaricati)
            {
                if (!this.isConnection())
                {
                    await new MessageDialog("Connessione Assente. L'applicazione non funzionarà correttamente").ShowAsync();
                    return;
                }
                try
                {
                    await new ManagerServices().GetDatiService(Convert.ToInt32(esito));
                }
                catch (Exception)
                {
                    new MessageDialog("Attenzione! Aggiornamento dei servizi. Ci scusiamo per il problema").ShowAsync();
                    Progress.IsActive = false;
                    return;
                }
                await MRS.Scrivi(DataFlowObject.Version.ToString());

                if (DataFlowObject.UpdateTipologia + DataFlowObject.UpdateDifficolta + DataFlowObject.UpdateDomande > 0)
                    SetPannelloUpdate();
                DataFlowObject.IsDatiCaricati = true;
            }
            ListTipologiaTest = DataFlowObject.ListTipologiaTest;
            this.DefaultViewModel["ListaTest"] = ListTipologiaTest;
            Progress.IsActive = false;

        }

        private void SetPannelloUpdate()
        {
            if (DataFlowObject.UpdateTipologia > 0)
                TxtUpdateTipologie.Text = (DataFlowObject.UpdateTipologia > 1) ? string.Format("{0} Tipologie", DataFlowObject.UpdateTipologia) : string.Format("{0} Tipologia", DataFlowObject.UpdateTipologia);
            else
                TxtUpdateTipologie.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            if (DataFlowObject.UpdateDifficolta > 0)
                TxtUpdateDifficolta.Text = string.Format("{0} Difficoltà", DataFlowObject.UpdateDifficolta);
            else
                TxtUpdateDifficolta.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            if (DataFlowObject.UpdateDomande > 0)
                TxtUpdateDomande.Text = (DataFlowObject.UpdateDomande > 1) ? string.Format("{0} Domande", DataFlowObject.UpdateDomande) : string.Format("{0} Domanda", DataFlowObject.UpdateDomande);
            else
                TxtUpdateDomande.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            Aggiornamenti.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }

        /// <summary>
        /// 
        /// </summary>
        private void AnimazioneSBHeader()
        {
            SBHeader.AutoReverse = true;
            SBHeader.RepeatBehavior = Windows.UI.Xaml.Media.Animation.RepeatBehavior.Forever;
            SBHeader.Begin();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SceltaTest_Click(object sender, RoutedEventArgs e)
        {
            var pulsante = (Button)e.OriginalSource;
            var idTest = (long)pulsante.Tag;
            DataFlowObject.TipologiaTest = ListTipologiaTest.Where(x => x.IDTest == idTest).Single();
            if (this.Frame != null)
                this.Frame.Navigate(typeof(ScegliDifficolta));
        }

        private void BtnBacheca_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            if (PopupBacheca.IsOpen)
                return;
            PopupBacheca.Child = new Bacheca(this);
            PopupBacheca.IsOpen = true;
        }

        private void BtnListaRisultati_Click(object sender, RoutedEventArgs e)
        {
            if (this.Frame != null)
                this.Frame.Navigate(typeof(ListaRisultati));
        }

        private void mail_Click(object sender, RoutedEventArgs e)
        {
            if (PopupBacheca.IsOpen)
                return;
            PopupBacheca.Child = new InvioSuggerimento(this);
            PopupBacheca.IsOpen = true;
        }

        private void BtnDB_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}